import { ElLoading, ElNotification } from "element-plus";
let loading: any = null;

// 显示loading
export const showLoading = (options?: { text: string; target: HTMLElement }) => {
  console.log("121");
  loading = ElLoading.service({
    lock: true,
    text: options?.text || "Loading",
    target: options?.target || document.body,
  });
};

// 隐藏loading
export const hideLoading = () => {
  loading && loading.close();
  loading = null;
};

// 通知提示框
export const toast = async (message: string, type = "success", dangerouslyUseHTMLString = false) => {
  await ElNotification.closeAll();
  ElNotification({
    //@ts-ignore
    message,
    type,
    dangerouslyUseHTMLString,
    duration: 3000
  });
};

/**
 * @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 * */
export const getShowMenuList = (menuList: Menu) => {
  let newMenuList: Menu = JSON.parse(JSON.stringify(menuList));
  newMenuList = sortMenuList(newMenuList);
  return newMenuList.filter((item) => {
    item.children?.length && (item.children = getShowMenuList(item.children));
    return item.meta?.isHide;
  });
};

/**
 * @description 使用递归排序
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export const sortMenuList = (menuList: any) => {
  const newMenuList: Menu = JSON.parse(JSON.stringify(menuList));
  return newMenuList
    .map((item) => {
      item.children?.length && (item.children = sortMenuList(item.children));
      return item;
    })
    .sort((a, b) => {
      return (a.meta?.sort || 0) - (b.meta?.sort || 0);
    });
};
/**
 * @description 使用递归扁平化菜单，方便添加动态路由
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export const getFlatMenuList = (menuList: Menu): Menu => {
  const newMenuList: Menu = JSON.parse(JSON.stringify(menuList));
  return newMenuList.flatMap((item) => [
    item,
    ...(item.children ? getFlatMenuList(item.children) : [])
  ]);
};

/**
 *  删除菜单下的权限
 */
const deleteMenuList = (menuList: any) => {
  const newMenuList = JSON.parse(JSON.stringify(menuList));
  return newMenuList.filter((item: any) => {
    item.children.length && (item.children = deleteMenuList(item.children));
    return item.type === 1;
  });
};

/**
 * @description 使用递归过格式化菜单字段
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export const filterMenuList = (menuList: any): any => {
  const newMenuList = JSON.parse(JSON.stringify(menuList));
  const newMenuList2 = deleteMenuList(newMenuList);
  return newMenuList2.map((item: any) => {
    if (item.type === 1) {
      if (item.children) {
        item.children = filterMenuList(item.children);
        return {
          path: item.routeAddress,
          name: item.componentName,
          component: item.componentUrl,
          children: item.children || [],
          meta: {
            title: item.menuName,
            icon: item.icon,
            isHide: item.showStatus,
            sort: item.sort
          }
        };
      }
    }
  });
};

/**
 * 金额转大写
 * @param account - 金额
 */
export const upperMoney = (account: number): string => {
  const money = parseFloat(account.toFixed(2));
  // 汉字的数字
  const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  // 基本单位
  const cnIntRadice = ["", "拾", "佰", "仟"];
  // 对应整数部分扩展单位
  const cnIntUnits = ["", "万", "亿", "兆"];
  // 对应小数部分单位
  const cnDecUnits = ["角", "分", "毫", "厘"];
  // 整数金额时后面跟的字符
  const cnInteger = "整";
  // 整型完以后的单位
  const cnIntLast = "元";
  // 最大处理的数字
  const maxNum = 9999999999999.99;
  // 金额整数部分
  let integerNum = "";
  // 金额小数部分
  let decimalNum = "";
  // 输出的中文金额字符串
  let chineseStr = "";
  // 分离金额后用的数组，预定义
  let parts: Array<string>;
  if (money >= maxNum) {
    // 超出最大处理数字
    return "";
  }
  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  // 转换为字符串
  let moneyStr = money.toString();
  if (money < 0) {
    // 负数判断
    moneyStr = moneyStr.slice(1);
  }
  if (moneyStr.indexOf(".") === -1) {
    integerNum = moneyStr;
    decimalNum = "";
  } else {
    parts = moneyStr.split(".");
    integerNum = parts[0] as string;
    decimalNum = parts[1] as string;
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    const IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i += 1) {
      const n = integerNum.substring(i, i + 1);
      const p = IntLen - i - 1;
      const q = p / 4;
      const m = p % 4;
      if (n === "0") {
        zeroCount += 1;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        // 归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n, 10)] + cnIntRadice[m];
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  // 小数部分
  if (decimalNum !== "") {
    const decLen = decimalNum.length;
    for (let i = 0; i < decLen; i += 1) {
      const n = decimalNum.substring(i, i + 1);
      if (n !== "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr === "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum === "") {
    chineseStr += cnInteger;
  }
  return (money < 0 ? "负" : "") + chineseStr;
};

/**
 * 图片压缩
 * @param file - 图片文件
 * @param quality - 压缩质量
 * @returns Promise<File>
 */
export const compressImage = (file: File, quality: number = 0.9) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const img = e.target!.result as string;
      const imgObj = new Image();
      imgObj.src = img;
      imgObj.onload = () => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        canvas.width = imgObj.width / 2;
        canvas.height = imgObj.height / 2;
        ctx!.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
        canvas.toBlob(
          (blob) => {
            resolve(new File([blob!], file.name, { type: file.type }));
          },
          "image/jpeg",
          quality
        );
      };
    };
  });
};
